<template>
  <div class="inner home-inner">
    <el-menu class="el-menu-demo" mode="horizontal" background-color="#545c64" text-color="#fff"
      active-text-color="#ffd04b" router>
      <div class="flex-grow" />
      <el-menu-item index="1" style="font-size: 28px;" route="/">IWu招聘</el-menu-item>
      <el-menu-item index="2" style="font-size: 20px" route="/">首页</el-menu-item>
      <div class="flex-grow" />
      <div class="mt-4">
        <el-input v-model="searchinput" placeholder="请输入" class="input-with-select">
          <template #prepend>
            <el-select v-model="select" placeholder="请选择" style="width: 115px">
              <el-option label="职位" value="job" />
              <el-option label="公司" value="enterprise" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="btn_search()" />
          </template>
        </el-input>
      </div>


      <div class="flex-grow" />

      <el-menu-item v-if="!proxy.$store.state.authState.isLogin || proxy.$store.state.authState.identity == 'enterprise'"
        index="3" style="font-size: 20px;" route="/login">登录</el-menu-item>
      <el-menu-item v-if="!proxy.$store.state.authState.isLogin || proxy.$store.state.authState.identity == 'enterprise'"
        index="4" style="font-size: 20px" route="/register">注册</el-menu-item>

      <el-sub-menu v-if="proxy.$store.state.authState.isLogin && proxy.$store.state.authState.identity == 'user'"
        index="5" style="font-size: 20px;margin-left: 100px;">
        <template #title>
          <img :src="avatar" style="height: 30px; width: 30px; border-radius: 100%;" alt="">
        </template>
        <el-menu-item index="2-1" route="/userhome">个人中心</el-menu-item>
        <el-menu-item index="2-3" @click="loginOut()" route="/">退出登录</el-menu-item>
      </el-sub-menu>

    </el-menu>



  </div>
</template>
<script lang='ts'>
import { reactive, ref, getCurrentInstance, onMounted, computed, watch, defineEmits, onBeforeMount } from "vue";
import { Search } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router';
import { useStore, mapState } from "vuex"
import { getAvatar, loginOu } from "@/api/authApi"
import { elmessage, data } from "@/hook/hook"
import { getAllJobInfo, getAllEInfo, searchJobs, searchEnterprises } from "@/api/authApi"
import { getEAvatar } from "@/api/enterpriseApi"
export default {
  name: 'Header',


  setup(props: any, context: any) {
    // console.log(123);
    // 头像
    // const avatar=require('/public/avatar.jpg')
    const avatar = ref("")
    // @ts-ignore
    const { proxy } = getCurrentInstance() // 1.获取proxy实例

    // 路由跳转
    const router = useRouter()
    const route = useRoute()

    const store = useStore()

    const activeIndex = ref("1");
    const activeIndex2 = ref("1");

    // 搜索


    const searchinput = ref('')
    const select = ref('job')


    const job = store.state.jobState.jobs
    const e = store.state.eState.Es
    // 回到主页
    const btn_back = () => {
      select.value="job"
      searchinput.value=""

      store.state.searchWd = ""
      store.state.searchType = ""
      router.replace("/")
    }
    const getValue=()=>{
      if (route.fullPath != "/") {
        // console.log(route.fullPath.split("/")[1].split("?"));
        if (route.fullPath.split("/")[1].split("?")[0] == "search") {
          const valueArr = route.fullPath.split("?")[1].split("&")
          if (valueArr.length == 1) {
            
            searchinput.value = ""
            select.value = valueArr[0].split("=")[1]
            
          } if (valueArr.length == 2) {
            
            
            select.value = valueArr[0].split("=")[1]
            searchinput.value =  decodeURI(valueArr[1].split("=")[1])
           
            
            
          }
        }

      }
    }
    // 获取hotJobs
    const getDatas = () => {
      store.state.jobState.jobs = []
      store.state.eState.Es = []
      // getValue()
      
      
      const searchData = {
        wd: searchinput
      }
      
      
      if (select.value == "job") {

        searchJobs(searchData).then((res: any) => {
          // console.log(res);
          

          res.data.jobs.forEach((valu: any, inde: any, sel: any) => {
            const data = { eId: valu.eId }
            getEAvatar(data).then((re: any) => {
              if (re.data.type == "image.jpeg/png") {
                store.state.jobState.jobs.push(
                  {
                    ...valu,
                    eAvatar: window.URL.createObjectURL(re.data)
                  }
                )
              } else {
                console.log(re.data);

              }

            })
          })
          setTimeout(() => {
            store.state.loading = false
            if (store.state.jobState.jobs.length != 0) {
              store.state.isGet = true
            } else {
              store.state.isGet = false
            }
          }, 1000);
        })
      }
      else if (select.value == "enterprise") {

        searchEnterprises(searchData).then((res: any) => {
          res.data.es.forEach((value: any, inde: any, sel: any) => {
            store.state.eState.Es.push(value)
          })
          setTimeout(() => {
            store.state.loading = false
            if (store.state.eState.Es != 0) {
              store.state.isGet = true
            } else {
              store.state.isGet = false
            }
          }, 1000);
        })

      }
    }
    const btn_search = () => {
      store.state.loading = true
      store.state.isGet = false
      
      getDatas()
      if (searchinput.value) {
        router.push({ name: 'SearchPage', query: { type: select.value, wd: searchinput.value } })
        store.commit("upSearch", { searchType: select.value, searchWd: searchinput.value })
      } else {
        searchinput.value = ""
        router.push({ name: 'SearchPage', query: { type: select.value } })
        store.commit("upSearch", { searchType: select.value, searchWd: searchinput.value })
      }
    }

    // 退出登录
    const loginOut = () => {
      loginOu(data())
      store.commit("loginOut")
      localStorage.clear()
      elmessage("退出成功", "success")
    }

    // 采用async
    // 头部获取头像
    const initAvatar = async () => {

      // if (store.state.userState.userBasicInfo.avatar == "") {
      // 请求后端，请求用户头像
      // if (data().token!=null){

      getAvatar(data()).then((res: any) => {
        if (res.data.type == "text/html") {
          // 返回text/html表示请求图片失败
          return
        } else {
          avatar.value = window.URL.createObjectURL(res.data)
          store.state.userState.userBasicInfo.avatar = avatar.value
        }
      }).catch(() => { })

      // }
    }
    const watchVuexAvatar = computed(() => store.state.userState.userBasicInfo.avatar)
    watch(watchVuexAvatar, (newval, oldval) => {
      avatar.value = store.state.userState.userBasicInfo.avatar
    }, { immediate: true, deep: true })


    onMounted(()=>{
      // getValue()
    })
    onBeforeMount(() => {
      if (route.fullPath!="/"){
        if (store.state.searchWd == "" && store.state.searchType == "") {
          
          searchinput.value = ""
          select.value = "job"
          
      } else {
        store.state.jobState.jobs = []
          store.state.eState.Es = []
        searchinput.value = store.state.searchWd
        select.value = store.state.searchType
        getDatas()
      }
      }else{
        select.value="job"
      searchinput.value=""
      }
      
      


      initAvatar()

    })



    return {
      avatar,
      proxy,
      // 搜索
      Search,
      searchinput,
      select,
      activeIndex,
      activeIndex2,
      btn_back,
      btn_search,
      // 退出登录
      loginOut,

    };

  }
}
</script>
<style scoped>
.el-menu {
  border-bottom: 0;
}

.el-menu-item.is-active {
  color: black !important;
}

.el-menu--horizontal .el-menu-item:not(.is-disabled):focus,
.el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
  background-color: #545c64;
}

.flex-grow {
  flex-grow: 0.25;
}

/* 搜索 */
.mt-4 {
  display: inline-flex;
  align-items: center;
  width: 400px;
}

.el-select {
  width: 90px !important;
  font-family: '微软雅黑';
  font-weight: 500;
}

/* .input-with-select .el-input-group__prepend { */
/* background-color: var(--el-fill-color-blank); */

/* } */

.inner {
  width: 1160px;
  margin: 0 auto;
}

.home-inner {
  max-width: 1160px;
}
</style>